#include "IOUringEventLoop.h"
#include "IOUringEventLoopThread.h"
#include "IOUringTcpServer.h"
#include "Logger.h"
#include <string.h>
using namespace std::placeholders;

void handle_accept(IOUringEventLoop *loop, struct io_uring_cqe *cqe) {
    int connfd = cqe->res;
    if (connfd >= 0) {
        loop->addRead(connfd, loop->ioUring()->kMaxMessageLen,
                      IOSQE_BUFFER_SELECT);
    }
}

void handle_read(IOUringEventLoop *loop, struct io_uring_cqe *cqe) {
    int bytesRead = cqe->res;
    int bid = cqe->flags >> 16;
    struct conn_info conni;
    memcpy(&conni, &cqe->user_data, sizeof(conni));

    if (cqe->res <= 0) {
        loop->addProvideBuf(bid);
        close(conni.fd_);
    } else {
        loop->addWrite(conni.fd_, bid, bytesRead, 0);
    }
}

void handle_write(IOUringEventLoop *loop, struct io_uring_cqe *cqe) {
    struct conn_info conni;
    memcpy(&conni, &cqe->user_data, sizeof(conni));

    loop->addProvideBuf(conni.bid_);
    loop->addRead(conni.fd_, loop->ioUring()->kMaxMessageLen,
                  IOSQE_BUFFER_SELECT);
}

int main() {
    int portno = 8000;
    IOUringTcpServer server(1, portno);
    server.setNewConnectionCallback(handle_accept);
    server.setReadCompleteCallback(handle_read);
    server.setWriteCompleteCallback(handle_write);
    server.start();
}
